package com.ilink.groundservice.service.impl.culture;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.groundservice.entity.PO.culture.Artwork;
import com.ilink.groundservice.entity.PO.dataset.DatasetMetadata;
import com.ilink.groundservice.entity.VO.culture.ArtworkResponse;
import com.ilink.groundservice.service.culture.ArtworkService;
import com.ilink.groundservice.mapper.culture.ArtworkMapper;
import com.ilink.ilinkapi.dto.ground.culture.ArtworkMetadataRequest;
import com.ilink.ilinkapi.dto.ground.culture.ArtworkRequest;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyTeacherCourse;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
* @author LENOVO
* @description 针对表【artworks】的数据库操作Service实现
* @createDate 2024-11-05 10:42:34
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class ArtworkServiceImpl extends ServiceImpl<ArtworkMapper, Artwork>
    implements ArtworkService {
    private final ArtworkMapper artworkMapper;
    private final OssService ossService;

    /**
     * @Author ZhangBo
     * @Description 分页返回作品元数据
     * @Date 15:20 2024/11/5
     * @Param [request]
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ilink.groundservice.entity.VO.culture.ArtworkResponse>
     **/
    @Override
    public IPage<ArtworkResponse> getArtworkMetadata(ArtworkMetadataRequest request) {
        try {
            log.info("解决3,4页一样的问题");
            int page = request.getPage();
            int size = request.getSize();

            LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();

            // 处理关键词查询
            if (request.getKeywords() != null && !request.getKeywords().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like(Artwork::getTitle, request.getKeywords())        // 标题中匹配关键词
                    .or()
                    .like(Artwork::getTag, request.getKeywords())       // 标签中匹配关键词
                    .or()
                    .like(Artwork::getUserName, request.getKeywords())   // 发布人中匹配关键词
                );
            }

            // 处理标签查询
            if (request.getTag() != null && !request.getTag().isEmpty()) {
                queryWrapper.like(Artwork::getTag, request.getTag());
            }

            // 按照点赞数和ID排序
            queryWrapper.orderByDesc(Artwork::getLikes)
                .orderByDesc(Artwork::getArtworkId);


            // 执行分页查询
            IPage<Artwork> artworkPage = this.page(new Page<>(page, size), queryWrapper);

            // 将查询结果转换为 ArtworkResponse 对象
            List<ArtworkResponse> artworkResponses = artworkPage.getRecords().stream()
                .map(artwork -> {
                    ArtworkResponse response = new ArtworkResponse();
                    response.setArtworkId(artwork.getArtworkId());
                    response.setTitle(artwork.getTitle());
                    response.setTag(artwork.getTag());
                    response.setUserName(artwork.getUserName());
                    response.setLikes(artwork.getLikes());
                    response.setCreatedAt(artwork.getCreatedAt());
                    String imagePath = ossService.getBucketFileUrl("ilink-aigc-migrate",
                        artwork.getImagePath());
                    if(imagePath == null)
                    {
                        log.error("作品未找到"+artwork.getArtworkId());
                        return null;
                    }
                    response.setImageUrl(imagePath);
                    return response;
                }).collect(Collectors.toList());

            // 返回分页结果
            Page<ArtworkResponse> artworkResponsePage = new Page<>(page, size);
            artworkResponsePage.setRecords(artworkResponses);
            artworkResponsePage.setTotal(artworkPage.getTotal());
            artworkResponsePage.setCurrent(artworkPage.getCurrent());
            artworkResponsePage.setSize(artworkPage.getSize());

            log.info("分页查询：页码 = " + page + ", 每页大小 = " + size);
            log.info("Total records: " + artworkPage.getTotal());
            log.info("Current page: " + artworkPage.getCurrent());

            return artworkResponsePage;
        } catch (Exception e) {
            log.error("函数getArtworkMetadata报错" + e);
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 批量上传作品
     * @Date 22:04 2024/11/5
     * @Param [artworkRequests, files]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @Override
    @Transactional
    public R uploadArtworksFromLocalFile() {
        try {
            // 1. 读取本地 Excel 文件并解析为 ArtworkRequest 列表
            String excelFilePath = "E:\\工作\\智链\\毛浚骁\\mjx.xlsx";
            File excelFile = new File(excelFilePath);
            if (!excelFile.exists()) {
                return R.error("Excel 文件不存在: " + excelFilePath);
            }

            FileInputStream fis = new FileInputStream(excelFile);
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);

            List<ArtworkRequest> artworkRequests = new ArrayList<>();
            for (Row row : sheet) {
                // 跳过标题行
                if (row.getRowNum() == 0) continue;

                ArtworkRequest artworkRequest = new ArtworkRequest();

                // 检查每个单元格是否为空
                artworkRequest.setUserName(row.getCell(1) != null ? row.getCell(1).getStringCellValue() : "");
                artworkRequest.setTitle(row.getCell(2) != null ? row.getCell(2).getStringCellValue() : "");
                artworkRequest.setTag(row.getCell(3) != null ? row.getCell(3).getStringCellValue() : "");

                artworkRequests.add(artworkRequest);
            }
            fis.close();

            // 打印 Excel 中的作品数量
            log.info("Excel 中的作品数量: " + artworkRequests.size());

            // 2. 读取本地图片文件夹中的所有图片
            File imageFolder = new File("E:\\工作\\智链\\毛浚骁\\images");
            if (!imageFolder.exists() || !imageFolder.isDirectory()) {
                return R.error("图片文件夹路径错误: " + imageFolder.getAbsolutePath());
            }

            String[] imageFiles = imageFolder.list((dir, name) -> name.endsWith(".png") || name.endsWith(".jpg"));
            if (imageFiles == null || imageFiles.length == 0) {
                return R.error("图片文件夹中没有符合条件的图片文件");
            }

            // 打印图片数量
            log.info("图片文件夹中的图片数量: " + imageFiles.length);

            if (artworkRequests.size() != imageFiles.length) {
                return R.error("Excel 中作品数量与图片数量不匹配");
            }

            // 3. 上传图片到 OSS 并保存到数据库
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            for (int i = 0; i < artworkRequests.size(); i++) {
                ArtworkRequest artworkRequest = artworkRequests.get(i);
                File imageFile = new File(imageFolder, imageFiles[i]);

                if (!imageFile.exists()) {
                    return R.error("图片文件不存在: " + imageFile.getAbsolutePath());
                }

                // 生成图片在 OSS 中的路径
                long artworkId = idGenerator.nextId();
                String objectName = "artworks/" + artworkId + getFileExtension(imageFile.getName());

                // 4. 将本地文件转换为 MultipartFile
                MultipartFile multipartFile = convertFileToMultipartFile(imageFile);
                if (multipartFile == null) {
                    return R.error("无法将文件转换为 MultipartFile: " + imageFile.getAbsolutePath());
                }

                // 5. 上传图片到 OSS
                boolean isUploaded = ossService.uploadBucketFile(multipartFile, "ilink-aigc-migrate", objectName);
                if (!isUploaded) {
                    return R.error("文件上传到 OSS 失败，文件名：" + objectName);
                }

                // 6. 保存 Artwork 数据到数据库
                Artwork artwork = new Artwork();
                artwork.setArtworkId(artworkId);
                artwork.setTitle(artworkRequest.getTitle());
                artwork.setTag(artworkRequest.getTag());
                artwork.setUserName(artworkRequest.getUserName());
                artwork.setLikes(0);  // 初始化点赞数
                artwork.setCreatedAt(new Date());
                artwork.setImagePath(objectName);

                this.save(artwork); // 保存到数据库
            }

            return R.ok("批量上传作品成功");

        } catch (Exception e) {
            log.error("批量上传作品失败: " + e.getMessage(), e);
            return R.error("批量上传作品失败: " + e.getMessage());
        }
    }


    private MultipartFile convertFileToMultipartFile(File file) throws FileNotFoundException {
        // 创建 FileItemFactory 和 DiskFileItem
        FileItemFactory factory = new DiskFileItemFactory();
        DiskFileItem fileItem = new DiskFileItem("file", "image/jpeg", false, file.getName(), (int) file.length(), file.getParentFile());

        // 使用 FileInputStream 读取文件内容
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            fileItem.getOutputStream().write(fileInputStream.readAllBytes());
        } catch (IOException e) {
            throw new RuntimeException("文件转换为 MultipartFile 时出错: " + file.getAbsolutePath(), e);
        }

        // 创建 CommonsMultipartFile 对象并返回
        return new CommonsMultipartFile(fileItem);
    }

    /**
     * @Author ZhangBo
     * @Description 获取文件后缀的方法
     * @Date 10:03 2024/11/6
     * @Param [fileName]
     * @return java.lang.String
     **/
    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return dotIndex == -1 ? "" : fileName.substring(dotIndex);
    }

    /**
     * @Author ZhangBo
     * @Description 作品点赞
     * @Date 10:07 2024/11/6
     * @Param [courseId]
     * @return boolean
     **/
    @Override
    @Transactional
    public boolean addArtworksLike(Long artworkId) {
        try {
            Artwork artwork = artworkMapper.selectById(artworkId);
            if (artwork == null) {
                log.error("没有找到作品" + artworkId);
                return false;
            }
            Integer likes = artwork.getLikes();
            artwork.setLikes(likes+1);
            artworkMapper.updateById(artwork);
            return true;
        } catch (Exception e) {
            log.error("addArtworksLike函数错误"+e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 返回最常用的标签
     * @Date 10:16 2024/11/6
     * @Param [num]
     * @return java.util.List<java.lang.String>
     **/
    @Override
    public List<String> getCommonTags(int num) {
        return artworkMapper.getCommonTags(num);
    }
}




